<?php

namespace app\admin\controller\pay;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Orders extends Backend
{
    
    /**
     * Orders模型对象
     * @var \app\admin\model\pay\Orders
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pay\Orders;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 升级派彩
     */
    public function payout()
    {
        ini_set("memory_limit","800M");
        set_time_limit(0);
        if($this->request->isPost()){
            $re = ["status"=>401,"msg"=>"选项错误"];
            $type = input("type");
            // 升级
            if($type == 1){// 归档流水
                $re = $this->save_user();
            } else if($type == 2){ // 晋级彩金
                $re = $this->up_money();
            } else if($type == 3){ // 每月好运金
                $re = $this->save_haoyun();
            }
            if($re["status"] == 200){
                $this->success();
            } else {
                $this->error($re['msg']);
            }
        }
        return $this->view->fetch();
    }


    // ==============================================================

    /**
     * 保存用户数据,归档流水
     */
    public function save_user()
    {
        $time = time();
        // 查询未导入的用户流水
        $data = Db::name("vip_orders")->field("*,SUM(money) AS sum_money")->where("status",0)->group("username,savetime")->select();
        //dump(count($data));die;
        if(empty($data)){
            return ["status"=>200,"msg"=>"操作成功"];
        }
        $ids = array_column($data,"id");
        // 保存到用户表数据
        foreach($data as $k=>$v) {
            $user = Db::name("vip_user")->where("username",$v["username"])->find();
            if(!empty($user)){
                Db::name("vip_user")->insert(['username'=>$v['username'],'level'=>0,'money'=>$v['money'],'createtime'=>$time,'updatetime'=>$time]);
            } else {
                Db::name("vip_user")->where("id",$user["id"])->setDec("money",$v["money"]);
            }
        }
        $count = count($data);
        Db::name("vip_orders")->where("id","IN",$ids)->update(['status'=>1]);
        return ["status"=>200,"msg"=>"保存{$count}条数据成功"];
    }




    // ==============================================================


    /**
     * 保存好运金
     */
    public function save_haoyun()
    {
        // 查询这个月有投注的用户【以您上个月18日至本月17日期间的有效投注计算，可得相对应的好运金】
        $time = time();
        $startTime = strtotime(date("Y-m-18",strtotime('last month')));
        $endTime = strtotime(date("Y-m-18",$time));
        $month = date("Y-m",$time);
        //$startTime= strtotime(date("Y-m-1",$time));
        //$endTime = strtotime(date('Y-m-1',strtotime('next month')));
        $data = Db::name("vip_orders")->alias("a")
            ->join("vip_user b","a.username = b.username")
            ->field("a.*,SUM(a.money) AS month_money,b.level")
            ->where("a.savetime >= $startTime AND a.savetime < $endTime")
            ->where("a.status",1)
            ->where("b.level > 0")
            ->group("a.username")
            ->select();
        //dump(Db::name("vip_orders")->getLastSql());
        //dump($data);
        $description_money = Db::name("vip_description")->order("save_money desc")->cache(true)->select();//奖金
        foreach($data as $k=>$v) {
            $haoyunMoney = $this->haoyun_money($v["level"],$v["month_money"],$description_money);
            if($haoyunMoney > 0) {
                $choumaData["username"] = $v["username"];
                $choumaData["savemoney"] = $v["month_money"];
                $choumaData["savetime"] = $month;
                $choumaData["status"] = 0;
                $user = Db::name("vip_haoyun")->where("username",$v["username"])->where("month",$month)->find();
                if(!empty($user)){
                    Db::name("vip_haoyun")->where("id",$user["id"])->update($data);
                } else {
                    Db::name("vip_haoyun")->insert($data);
                }
            }
        }
        return ["status"=>200,"msg"=>"ok"];
    }
    /**
     * 查询当前彩金对应奖励
     */
    public function haoyun_money($level,$save_money,$caijinData)
    {
        $money = 0;
        foreach($caijinData as $v){
            if($save_money >= $v["save_money"] && $level >= $v["level_start"]){
                $money = $v["money"];
                break;
            }
        }
        return $money;
    }


    //=========================================================



    /**
     * 升级检测
     */
    public function up_money()
    {
        $data = Db::name("vip_user")->select();
        $description = Db::name("vip_description")->order("save_money desc")->cache(true)->select();//奖金
        foreach($data as $v){
            // 获取当前等级
            $level = $this->level($v["money"],$description);
            // 不相等时晋级
            $this->uplevel($v["level"],$level,$v["username"],$description);
        }
        return ["status"=>200,"msg"=>"ok"];
    }
    /**
     * 判断当前等级
     */
    public function level($userMoney,$level_money)
    {
        foreach($level_money as $v){
            if($userMoney > $v['save_money']){
                return $v['level'];
            }
        }
        return 0;
    }
    /**
     * 判断是否晋级
     */
    public function uplevel($level,$now_level,$username,$description)
    {
        if($now_level > $level){
            $jiangli = [];
            foreach($description as $k=>$v){
                $jiangli["username"] = $username;
                $jiangli["money"] = $v["money"];
                $jiangli["level"] = $v["level"];
                $jiangli["status"] = 0;
                $jiangli["createtime"] = time();
            }
            if(!empty($jiangli)){
                Db::name("vip_jiangli")->insert($jiangli);
            }
        }
    }

}
